import Vue from 'vue'
import VueRouter from 'vue-router'
import {_get} from '../network'
// 引入组件
const Home = () => import("../views/Home")
const Disk = () => import("../views/Disk")
const Error = () => import("../views/Error")
const Preview = () => import("../views/Preview")
const UserCenter = () => import("../views/UserCenter")
const Admin = () => import("../views/Admin")

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: { path: '/disk/all', query: { path: '/' }}
    },
    {
        name: '首页',
        path: '/home',
        component: Home
    },
    {
        name: '文件预览',
        path: '/preview',
        meta: {
            role: 'user'
        },
        component: Preview
    },
    {
        name: '用户中心',
        path: '/user-center/:operation',
        meta: {
            role: 'all'
        },
        component: UserCenter
    },
    {
        name: '管理员界面',
        path: '/admin',
        meta: {
            role: 'admin'
        },
        component: Admin
    },
    {
        name: '我的网盘',
        path: '/disk/:category',
        meta: {
            role: 'user'
        },
        component: Disk
    },
    {
        name: 'error',
        path: '*',
        component: Error
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    let role = to.meta.role;
    document.title = to.name;
    if (role === undefined) {
        next();
    } else {
        // 没有用户数据
        if (sessionStorage.getItem("user") === null && sessionStorage.getItem("admin") === null) {
            _get({
                url: 'open/login-info'
            }).then(rsp => {
                if (rsp.data.code === "00000") {
                    sessionStorage.setItem(rsp.data.object.role, rsp.data.object.username)
                    if (role === "user" && sessionStorage.getItem("user")) {
                        next();
                    } else if (role === "admin" && sessionStorage.getItem("admin")){
                        next();
                    } else if (role === 'all' && (sessionStorage.getItem('user') || sessionStorage.getItem('admin'))) {
                        next();
                    } else {
                        next("/home");
                    }
                } else {
                    next("/home")
                }
            })
        } else {
            if (role === "user" && sessionStorage.getItem("user")) {
                next();
            } else if (role === "admin" && sessionStorage.getItem("admin")){
                next();
            } else if (role === 'all' && (sessionStorage.getItem('user') || sessionStorage.getItem('admin'))) {
                next();
            } else {
                next("/home");
            }
        }
    }
})

export default router
